package com.fare.taluo.util;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

	/**
	 *  以get的方式访问url
	 * @param httpclient
	 * @param url
	 * @return
	 */
	public static HttpResponse processGet(HttpClient httpclient, String url,
			Cookie[] cookies) {
		HttpResponse response = null;

		HttpGet httpget = new HttpGet(url);
		
		HttpHost targetHost =new HttpHost("flight.qunar.com");


		
		try {
			if (cookies != null) {
				httpget.setHeader("cookies", cookies.toString());
			}

			HttpContext localContext = new BasicHttpContext();

			CookieStore cookieStore =new BasicCookieStore();

			//	QN1	wKgZEE+yBc4qyVtiM9IxAg==					
			BasicClientCookie cookie=new BasicClientCookie("QN1","wKgZEE+yBc4qyVtiM9IxAg==");
			cookieStore.addCookie(cookie);			
			
			//已发送	QunarGlobal	192.168.0.83_43db7ffb_1374f507c2e_2a70|1337066957937				
			                  //192.168.0.83_43db7ffb_1374f507c2e_2a70|1337066957937
			BasicClientCookie cookie1=new BasicClientCookie("QunarGlobal","192.168.0.83_43db7ffb_1374f507c2e_2a70|1337066957937");
			cookieStore.addCookie(cookie1);
			
			
			//已发送	JSESSIONID	E7CD6A193998092AF96667BB7F9CCE12	
			//JSESSIONID=2B308158FE8F3E12620A949E4FC9806C
			BasicClientCookie cookie2=new BasicClientCookie("JSESSIONID","B588E288CF1A5A17E74D37BC39F06AE3");
			cookieStore.addCookie(cookie2);
			
			localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			
			response = httpclient.execute(targetHost,httpget, localContext);
//			
			CookieOrigin cookieOrigin = (CookieOrigin) localContext
					.getAttribute(ClientContext.COOKIE_ORIGIN);
			System.out.println("Cookie origin: " + cookieOrigin);
			CookieSpec cookieSpec = (CookieSpec) localContext
					.getAttribute(ClientContext.COOKIE_SPEC);
			System.out.println("Cookie spec used: " + cookieSpec);

			CookieStore cookieStore1 =(CookieStore)localContext.getAttribute(ClientContext.COOKIE_STORE);
			if (cookieStore1!=null){
				if (cookieStore1.getCookies()!=null){
					System.out.println("Cookie cookieStore  " + cookieStore1.getCookies().size());
				}
				
			}
		
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return response;
	}

	/**
	 *  以get的方式访问url
	 * @param httpclient
	 * @param Url
	 * @return
	 */
	public static HttpResponse processPost(HttpClient httpclient, String url) {
		HttpResponse response = null;

		HttpPost httpPost = new HttpPost(url);
		try {
			response = httpclient.execute(httpPost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return response;
	}

	/**
	 * 获取页面源码
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	public static String getPageHtmlCodeStr(HttpResponse response,
			HttpClient httpclient) throws Exception {
		String resHtml = "";

		System.out.println("----------------------------------------");
		System.out.println("Location: " + response.getLastHeader("Location"));
		System.out.println(response.getStatusLine().getStatusCode());
		System.out.println(response.getLastHeader("Content-Type"));
		System.out.println(response.getLastHeader("Content-Length"));

		System.out.println("----------------------------------------");

		// 判断页面返回状态判断是否进行转向抓取新链接
		int statusCode = response.getStatusLine().getStatusCode();
		if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
				|| (statusCode == HttpStatus.SC_SEE_OTHER)
				|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
			// 此处重定向处理  此处还未验证
			String newUri = response.getLastHeader("Location").getValue();
			httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(newUri);
			response = httpclient.execute(httpget);

		}

		// Get hold of the response entity
		HttpEntity entity = response.getEntity();

		// 查看所有返回头部信息
		Header headers[] = response.getAllHeaders();
		int ii = 0;
		while (ii < headers.length) {
			System.out.println(headers[ii].getName() + ": "
					+ headers[ii].getValue());
			++ii;
		}

		// If the response does not enclose an entity, there is no need
		// to bother about connection release
		if (entity != null) {
			// 将源码流保存在一个byte数组当中，因为可能需要两次用到该流，
			byte[] bytes = EntityUtils.toByteArray(entity);
			String charSet = "";

			// 如果头部Content-Type中包含了编码信息，那么我们可以直接在此处获取
			charSet = EntityUtils.getContentCharSet(entity);

			System.out.println("In header: " + charSet);
			// 如果头部中没有，那么我们需要 查看页面源码，这个方法虽然不能说完全正确，因为有些粗糙的网页编码者没有在页面中写头部编码信息
			if (charSet == "") {
				String regEx = "(?=<meta).*?(?<=charset=[\\'|\\\"]?)([[a-z]|[A-Z]|[0-9]|-]*)";
				Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);

				Matcher m = p.matcher(new String(bytes)); // 默认编码转成字符串，因为我们的匹配中无中文，所以串中可能的乱码对我们没有影响
				boolean result = m.find();
				if (m.groupCount() == 1) {
					charSet = m.group(1);
				} else {
					charSet = "";
				}
			}

			if (charSet != null) {
				if ("".equals(charSet.trim())) {
					charSet = "utf-8";

				}
			} else {
				charSet = "utf-8";
			}

			System.out.println("Last get: " + charSet);
			resHtml=new String(bytes, charSet);
			// 至此，我们可以将原byte数组按照正常编码专成字符串输出（如果找到了编码的话）
//			System.out.println("Encoding string is: "
//					+ resHtml);
		}

		return resHtml;
	}

	/**
	 * 获取代理连接
	 * @param proxyHost
	 * @param proxyPort
	 * @return
	 */
	public static HttpClient getProxyHttpClient(String proxyHost, int proxyPort) {
		int BUFFER_SIZE = 8192;
		String USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB6 (.NET CLR 3.5.30729)";
		int CONN_TIME_OUT = 20 * 1000;
		int READ_TIME_OUT = 20 * 1000;

		// 创建 HttpParams 以用来设置 HTTP 参数（这一部分不是必需的）   
		HttpParams httpParams = new BasicHttpParams();

		// 设置连接超时和 Socket 超时，以及 Socket 缓存大小   
		HttpConnectionParams.setConnectionTimeout(httpParams, CONN_TIME_OUT);
		HttpConnectionParams.setSoTimeout(httpParams, READ_TIME_OUT);
		HttpConnectionParams.setSocketBufferSize(httpParams, BUFFER_SIZE);

		// 设置重定向，缺省为 true   
		HttpClientParams.setRedirecting(httpParams, true);

		//		String proxyHost = "10.101.1.6";
		//		int proxyPort = 80;
		// proxyHost = "10.101.1.6";
		// proxyPort = 80;
		HttpHost proxy = new HttpHost(proxyHost, proxyPort);

		httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

		// 设置 user agent   
		String userAgent = USER_AGENT;
		HttpProtocolParams.setUserAgent(httpParams, userAgent);

		HttpClient httpClient = new DefaultHttpClient(httpParams);

		return httpClient;
	}

}
